//
// Created by Zeppyrz on 2025/11/6.
//

#include "UploadTask.h"

#include <cstring>
#include <iostream>

namespace ZeDiskGUI {

using namespace ZeDisk;

void UploadTask::HandleMessage(const ZeDisk::Message* msg) {
  CommonTask::HandleMessage(msg);
  switch (msg->head.type) {
    case MSG_TYPE_UPLOAD_ACCEPT:
      BeginWrite();
      break;
    case MSG_TYPE_UPLOAD_COMPLETE:
      // 刷新界面
      std::cout << "[INFO] upload complete" << std::endl;
      upload_complete_callback_();
      break;
    default:
      break;
  }
}

void UploadTask::WriteCallback() {
  CommonTask::WriteCallback();

  if (!file_.is_open()) {
    return;
  }

  file_.read(read_buffer_, sizeof(read_buffer_));
  int len = file_.gcount();
  if (len <= 0) {
    file_.close();
    return;
  }
  WriteRawMessage(read_buffer_, len);
  if (file_.eof()) {
    file_.close();
  }
}

void UploadTask::ConnectCallback() {
  CommonTask::ConnectCallback();
  if (file_path_.empty()) {
    std::cout << "[ERROR] file path is empty" << std::endl;
    return;
  }
  // 打开本地文件
  // 打开文件跳转到结尾i获取文件大小
  file_.open(file_path_, std::ios::in | std::ios::binary | std::ios::ate);
  if (!file_.is_open()) {
    std::cout << "[ERROR] open file: " << file_path_ << " error" << std::endl;
    return;
  }

  // 获取文件 名称 大小
  file_size_ = file_.tellg();
  file_.seekg(0, std::ios::beg);
  std::cout << "[INFO] open file: " << file_path_ << " size: " << file_size_
            << std::endl;

  int pos = file_path_.find_last_of('/');
  if (pos == std::string::npos) pos = 0;
  std::string filename(file_path_.substr(pos, file_path_.size() - pos));

  char buf[1024] = {0};
  snprintf(buf, sizeof(buf), "%s,%d", filename.c_str(), file_size_);

  // 发送上传请求
  Message msg;
  msg.head.type = MSG_TYPE_UPLOAD_INFO;
  msg.head.size = strlen(buf);
  msg.data = buf;
  WriteMessage(&msg);
}

bool UploadTask::Stop() {
  if (file_.is_open()) file_.close();
  return CommonTask::Stop();
}

}  // namespace ZeDiskGUI